import java.util.*;

/**
 * @ClassName Offer32III
 * @Description 剑指 Offer 32 - III. 从上到下打印二叉树 III
 * @Author clockTown
 * @Date 2021/8/17 10:51
 * @Version 1.0
 */
class Offer32III {
}

/**
 * BFS
 */
class Offer32IIIV0 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        queue.offer(root);
        boolean left2Right = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                level.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            if (left2Right){
                left2Right = false;
            }else {
                Collections.reverse(level);
                left2Right = true;
            }
            res.add(level);

        }
        return res;
    }
}